package ink.tsg.flink.aggregate;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author tsg
 * @version 1.0
 * @description: TODO
 * @date 2022/5/18 9:29
 */
public class TestAggregateAndProcessFunction {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        DataStreamSource<TempRecord> source = env.fromElements(
                new TempRecord("江苏","苏州","1",20.5, LocalDateTime.parse("2021-01-29 16:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
                new TempRecord("江苏","苏州","1",21.5, LocalDateTime.parse("2021-01-29 16:00:02", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
                new TempRecord("江苏","苏州","1",22.5, LocalDateTime.parse("2021-01-29 16:00:03", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
                new TempRecord("江苏","苏州","1",23.5, LocalDateTime.parse("2021-01-29 16:00:04", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
                new TempRecord("江苏","苏州","1",20.5, LocalDateTime.parse("2021-01-29 16:00:05", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))),
                new TempRecord("江苏","苏州","1",19.5, LocalDateTime.parse("2021-01-29 16:00:06", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
        );
        SingleOutputStreamOperator<TempRecord> dataStream = source
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<TempRecord>forBoundedOutOfOrderness(Duration.ofSeconds(0))
                                .withTimestampAssigner(new SerializableTimestampAssigner<TempRecord>() {

                                    @Override
                                    public long extractTimestamp(TempRecord element, long recordTimestamp) {
                                        return element.getTimeEpochMilli();
                                    }
                                })
                );
        SingleOutputStreamOperator<TempRecordAggsResult> result = dataStream
                .keyBy(TempRecord::getCity)
                .window(TumblingEventTimeWindows.of(Time.seconds(30)))
                .aggregate(new TempRecordUtils.MyAggregateFunction(),//增量计算
                        new TempRecordUtils.MyProcessWindow());//全量计算

        result.print();

        env.execute();
    }

}
